 //
//  SSSMerchantManagementViewController.m
//  SSSMerchant
//
//  Created by xnxin on 2017/3/25.
//  Copyright © 2017年 xnxin. All rights reserved.
//

#import "SSSMerchantManagementViewController.h"
#import "UIStoryboard+XHAdd.h"
#import "UIButtonAdditions.h"
#import "PhotoBrowseView.h"
#import "GYZDatePicker.h"
#import "JFImagePickerController.h"
#import "ImagePickerTool.h"
#import "SSSMerchantModel.h"
#import "ImageBrowserManager.h"
#import "NSString+extension.h"
#import <CoreLocation/CoreLocation.h>
#import "UINavigationController+QMUI.h"
#import "NSString+judge.h"
#define datePickerH 250
@interface SSSMerchantManagementViewController ()<JFImagePickerDelegate,PhotoBrowseViewDelegate,GYZDatePickerDelegate,CLLocationManagerDelegate,UIAlertViewDelegate,UITextViewDelegate,UITextFieldDelegate,ImagePickerToolDelegate>
{
    
    UIButton *_selectedTimeBtn;//当前选择时间的btn
    CLLocationCoordinate2D _coordinate;
    BOOL _mainPhotoSelected;//是否在选择主图
    BOOL _isEdit;//是否编辑过
    
    //    NSArray<UIImage *> *_netImages;//从网或上加载的图片数组
}

@property (weak, nonatomic) IBOutlet UITextField *merchantName;
@property (weak, nonatomic) IBOutlet UITextField *merchantType;
@property (weak, nonatomic) IBOutlet UITextField *merchantPhone;
@property (weak, nonatomic) IBOutlet UIButton *beginTime;
@property (weak, nonatomic) IBOutlet UIButton *closeTime;
@property (weak, nonatomic) IBOutlet QMUITextView *merchantDescription;
@property (weak, nonatomic) IBOutlet UILabel *merchantAddress;
@property (weak, nonatomic) IBOutlet PhotoBrowseView *photoBrowseView;
@property (strong, nonatomic) IBOutlet QMUIButton *saveButton;
@property (nonatomic,strong)  GYZDatePicker *datePicker;
@property (nonatomic, strong) CLLocationManager* locationManager;
@property (weak, nonatomic) IBOutlet UIButton *mainPhotoButton;
@property (weak, nonatomic) IBOutlet UIButton *mainPhotoCloseButton;//主图关闭按钮
@property (nonatomic,strong) UIImage *mainImage;//主图
@property (nonatomic,strong) SSSMerchantModel *merchantModel;
@end

@implementation SSSMerchantManagementViewController

#pragma mark -
#pragma mark LifeCycle

- (void)awakeFromNib {
    [super awakeFromNib];
    
    _isEdit=NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
    [self.datePicker removeFromSuperview];
    self.datePicker=nil;
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"店铺管理";
    self.saveButton.layer.cornerRadius = 5;
    self.saveButton.normalTitleColor = [UIColor whiteColor];
    _photoBrowseView.hiddenTopBar=YES;
    _photoBrowseView.delegate=self;
    _photoBrowseView.currentController=self;
    _photoBrowseView.backgroundColor=[UIColor whiteColor];
    [ImagePickerTool sharedManager].delegate=self;
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    if ([self isLocationOpen]==YES) {
        [self findMe];
    }
    _merchantModel=[[SSSMerchantModel alloc] init];
    [self netForMerchantDetail];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:_merchantPhone];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewChange:) name:UITextViewTextDidChangeNotification object:_merchantDescription];
    }
#pragma mark -   拦截返回按钮事件
-(BOOL)shouldHoldBackButtonEvent{
    return YES;
}
-(BOOL)canPopViewController{
    if (_isEdit==NO) {
        return YES;
    }
    
    XXAlertView *alert=[XXAlertView alertViewWithTitle:@"资料尚未保存，确认返回？" detail:@"" redButtonTitle:@"是的" otherbuttonTitle:@[@"取消"]];
    alert.alertViewRedButtonClickBlock=^{
        //返回
        [JFImagePickerController clear];
        [self.navigationController popViewControllerAnimated:YES];
        
    };
    [alert showAlertView];
    
    return NO;
}
#pragma mark - net
-(void)netForMerchantDetail{
    //[ZDNetManager zd_requestWithType:ZDHttpRequestTypePost UrlString:kConfigPath(kMerchantDetail) Parameters:nil SuccessBlock:^(id responseObj) {
    //    if (kResponseStatus==0) {
    //     //    }
    //    else showTipHudStr(kResponseMessage);
    //} FailureBlock:^(NSError *error) {
    //
    //} progress:nil];
    [[XHRequestManager manager] postRequest:kConfigPath(kMerchantDetail) params:nil success:^(id  _Nonnull responseObj) {
        
        if (kResponseStatus == 0) {
            _merchantModel=   [SSSMerchantModel mj_objectWithKeyValues:kResponseData];
            [self configShowData];
        }
        
        else showTipHudStr(kResponseMessage);
        
    } failure:^(NSError * _Nonnull error) {
        
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
        
    }];
    
}

-(void)netForImageUrlWithImages:(NSArray *)images successBlock:(void (^)(NSString *imageUrl))success{
    
    
    [ZDNetManager multipartUploadWithURL:kConfigPath(kImageUp) parameters:nil images:images name:@"files" fileNames:nil progress:nil success:^(id responseObj) {
        if (kResponseStatus==0) {
            success( kResponseData[@"path"]);
        }
        else showTipHudStr(kResponseMessage);
    } failure:^(NSError *error) {
        
    }];
    //    [[XHRequestManager manager] postRequest:kConfigPath(kImageUp) params:nil success:^(id  _Nonnull responseObj) {
    //        if (kResponseStatus==0) {
    //            success( kResponseData[@"path"]);
    //        }
    //        else showTipHudStr(kResponseMessage);
    //
    //    } failure:^(NSError * _Nonnull error) {
    //
    //        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
    //
    //    }];
    
    
}
-(void)netForUploadMerchantWithParam:(NSDictionary *)param successBlock:(void (^)(id response))success{
    
    
    //
    //    [ZDNetManager zd_requestWithType:ZDHttpRequestTypePost UrlString:kConfigPath(kMerchantUpload) Parameters:param SuccessBlock:^(id responseObj) {
    //         [QMUITips hideAllToastInView:kKeyWindow animated:YES];
    //        if (kResponseStatus==0) {
    //            success(responseObj);
    //        }
    //        else showTipHudStr(kResponseMessage);
    //    } FailureBlock:^(NSError *error) {
    //         [QMUITips hideAllToastInView:kKeyWindow animated:YES];
    //    } progress:nil];
    //
    [[XHRequestManager manager] postRequest:kConfigPath(kMerchantUpload) params:param success:^(id  _Nonnull responseObj) {
        [QMUITips hideAllToastInView:kKeyWindow animated:YES];
        if (kResponseStatus==0) {
            success(responseObj);
        }
        else showTipHudStr(kResponseMessage);
    } failure:^(NSError * _Nonnull error) {
        
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
        
    }];
}

-(void)configShowData{
    _merchantName.text=_merchantModel.bName;
    _merchantType.text=_merchantModel.operateTypeName;
    _merchantPhone.text=_merchantModel.phone;
    if (_merchantModel.openTime.length>0) {
        [_beginTime setTitle:_merchantModel.openTime forState:UIControlStateNormal];
    }
    
    if (_merchantModel.closeTime.length>0) {
        [_closeTime setTitle:_merchantModel.closeTime forState:UIControlStateNormal];
    }
    _merchantDescription.text=_merchantModel.intro;
    _merchantAddress.text=_merchantModel.businessAddress;
    
    NSArray *urls=[_merchantModel.showPics componentsSeparatedByString:@","];
    self.photoBrowseView.photoUrls=urls;
    [_mainPhotoButton sd_setImageWithURL:kConfigImageUrl(_merchantModel.businessPhoto)  forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_adphoto"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.mainImage=image;
        
    }];
}





#pragma mark - tableview
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==5) {
        [self datePickerShow];
    }
    
    
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self datePickerHidden];
    [self.view endEditing:YES];
}
#pragma mark - UITextViewDelegate
-(void)textViewDidBeginEditing:(UITextView *)textView{
    [self datePickerHidden];
}
#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [self datePickerHidden];
    return YES;
}
#pragma mark - DatePickerDelegate
- (void)datePicker:(GYZDatePicker *)datePicker didSelectDate:(GYZDatePickerModel *)datePickerDate {
    NSString *dateStr = [NSString stringWithFormat:@"%@:%@",
                         datePickerDate.hour,
                         datePickerDate.minute];
    //    时间转为时间戳
    
    if (_selectedTimeBtn.tag-200==0) {
        //开始时间
        _merchantModel.openTime=dateStr;
    }
    if (_selectedTimeBtn.tag-200==1) {
        //结束时间
        _merchantModel.closeTime=dateStr;
    }
    [_selectedTimeBtn setTitle:dateStr forState:UIControlStateNormal];
    _isEdit=YES;
}


#pragma mark - JFImagePickerControllerDelegate
- (void)imagePickerDidFinished:(JFImagePickerController *)picker {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
    NSMutableArray *thumbs = [NSMutableArray array];//装小图
    NSMutableArray *high_temp = [NSMutableArray array];//装高清图
    NSMutableArray *arr=[NSMutableArray array];
    
    for (ALAsset *asset in picker.assets) {
        UIImage *thumbImage=[UIImage imageWithCGImage:[asset thumbnail]];
        //先加载小图  再加载高清图
        [thumbs addObject:thumbImage];
    }
    [arr addObjectsFromArray: self.photoBrowseView.netImages];
    [arr addObjectsFromArray:thumbs];
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // [UIImage imageWithCGImage:[representation fullResolutionImage]];这一步很耗时  另开线程
        
        for (ALAsset *asset in picker.assets) {
            ALAssetRepresentation *representation = [asset defaultRepresentation];
            UIImage *image = [UIImage imageWithCGImage:[representation fullResolutionImage]];
            [high_temp addObject:image];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调通知主线程刷新，
            [arr removeAllObjects];
            [arr addObjectsFromArray: self.photoBrowseView.netImages];
            [arr addObjectsFromArray:high_temp];
            self.photoBrowseView.photos=arr;
            
        });
    });
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    _isEdit=YES;
}


- (void)imagePickerDidCancel:(JFImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //    [JFImagePickerController clear ];
    
}


#pragma mark - ImagePickerToolDelegate
-(void)imagePickerControllerDidCancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didPicker:(UIImage *)image userInfo:(NSDictionary *)info {
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);//把图片存到图片库
        //
    }else{
        if (_mainPhotoSelected==YES) {
            self.mainImage=image;
            
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    _isEdit=YES;
    
}
//将图片写入相册完成时候调用 （即调用了UIImageWriteToSavedPhotosAlbum后回调）
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo
{
    
    if (error != NULL)
    {
    }
    else  // No errors
    {
        if (_mainPhotoSelected==YES) {
            self.mainImage=image;
        }
        else{
            
            NSMutableArray *temp= [NSMutableArray arrayWithArray:self.photoBrowseView.photos];
            UIImage *compactImage=[image scaledToSize:CGSizeMake(800, 800)];
            [temp addObject:compactImage];
            self.photoBrowseView.photos =temp;
            
            NSMutableArray *tempPhoto=[NSMutableArray arrayWithArray:self.photoBrowseView.photos];
            [tempPhoto removeObjectsInArray:self.photoBrowseView.netImages];

            ASSETHELPER.cameraAssets=[tempPhoto mutableCopy];
            ASSETHELPER.isFirstOpenCamera=YES;
            [ASSETHELPER getPhotoListOfGroupByIndex:ASSETHELPER.currentGroupIndex result:^(NSArray *r) {
                ASSETHELPER.isFirstOpenCamera=NO;
                //更新坐标
                NSMutableArray *photos=[NSMutableArray array];
                
                [ASSETHELPER.selectdAssets addObject:[[ASSETHELPER assetPhotos] firstObject]];
                 ASSETHELPER.cameraAssets=[temp lastObject];
                
                [ASSETHELPER.selectdPhotos enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    [photos addObject:@{@"indexpath":@([dict[@"indexpath"] intValue]+1),@"location":@(idx+1)}];
                    NSLog(@"%@",dict);
                    
                    
                }];
                [photos addObject:@{@"indexpath":@0,@"location":@0}];//添加新拍的那张
                
                NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:@"location" ascending:YES];
                [photos sortUsingDescriptors:@[desc]];
                
                ASSETHELPER.selectdPhotos =[NSMutableArray arrayWithArray:photos];
                
                             
            }];
            
        }

        
    
    }
}
#pragma mark - PhotoBrowseViewDelegate
#pragma mark 添加多张照片
-(void)photoBrowseViewAddPhoto{
    _mainPhotoSelected=NO;
    [self selectPhotos];
    
}
//删除照片
-(void)photoBrowseViewDelete:(NSInteger)indexpath cell:(PhotoBrowseViewCell *)cell{
    //删除的是网络上的照片
    if ([self.photoBrowseView.netImages containsObject:cell.image]) {
        
        
        [self.photoBrowseView.netImages removeObject:cell.image];
        ASSETHELPER.currentPhotosCount=self.photoBrowseView.netImages.count;
        return;
    }
    if(ASSETHELPER.selectdAssets.count==0)
    {
        return;
    }
    
    
    
    
    
    NSMutableArray *temp=[NSMutableArray arrayWithArray:self.photoBrowseView.photos];
    [temp removeObjectsInArray:self.photoBrowseView.netImages];
    
    
    __block NSInteger  index=[temp indexOfObject:cell.image];//
    [ASSETHELPER.selectdAssets removeObjectAtIndex:index];
    [ASSETHELPER.selectdPhotos removeObjectAtIndex:index ];
    
    [ASSETHELPER.selectdPhotos enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([dict[@"location"]  intValue]>=index)
        {
            //重新排序   重新设置location 让后面的成员补位！！
            [ASSETHELPER.selectdPhotos replaceObjectAtIndex:idx withObject:@{@"indexpath":dict[@"indexpath"],@"location":@(index)}];
            index++;
            
        }
    }];
    
    
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    // 1.获取用户位置的对象
    CLLocation *location = [locations lastObject];
    _coordinate = location.coordinate;
    NSLog(@"纬度:%f 经度:%f", _coordinate.latitude, _coordinate.longitude);
    
    // 2.停止定位
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    if (error.code == kCLErrorDenied) {
        
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
    [manager stopUpdatingLocation];
}
#pragma mark - UIAlertView
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0)//确认跳转设置
    {  //跳转到定位设置
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    
}
#pragma mark -
#pragma mark note
-(void)textFieldChange:(NSNotification *)note{
    _merchantModel.phone=  _merchantPhone.text;
    _isEdit=YES;
}
-(void)textViewChange:(NSNotification *)note{
    
    _merchantModel.intro=  _merchantDescription.text;
}

#pragma mark -
#pragma mark action
#pragma mark     保存店铺信息


- (IBAction)save:(id)sender {
    
    if ([self isLocationOpen]==NO) {
        return;
    }
    if ([self isMerchantInfoComplete]==NO) {
        return;
    }
    [QMUITips showLoading:@"正在上传中..." inView:kKeyWindow];
    
    // 群组－统一监控一组任务
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t q = dispatch_get_global_queue(0, 0);
    
    // 1> 入组 -> 之后的 block 会被 group 监听
    // dispatch_group_enter 一定和 dispatch_group_leave 要配对出现
    dispatch_group_enter(group);
    dispatch_async(q, ^{
        //主图地址
        [self netForImageUrlWithImages:@[_mainImage] successBlock:^(NSString *imageUrl) {
            _merchantModel.businessPhoto=imageUrl;
            // block 的末尾，所有任务执行完毕后，添加一个出组
            dispatch_group_leave(group);
        }];
    });
    
    //  再次入组
    dispatch_group_enter(group);
    dispatch_async(q, ^{
        //展示图（多图）
        [self netForImageUrlWithImages:self.photoBrowseView.photos successBlock:^(NSString *imageUrl) {
            _merchantModel.showPics=imageUrl;
            // block 的末尾，所有任务执行完毕后，添加一个出组
            dispatch_group_leave(group);
            
        }];
    });
    
    // 群组结束
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        _merchantModel.latitude=[NSString stringWithFormat:@"%f", _coordinate.latitude];
        _merchantModel.longitude=[NSString stringWithFormat:@"%f", _coordinate.longitude];
        
        NSMutableDictionary *dict=   [_merchantModel mj_keyValues];
        [self netForUploadMerchantWithParam:dict successBlock:^(id response) {
            [JFImagePickerController clear];
            [QMUITips showSucceed:@"保存成功" inView:kKeyWindow hideAfterDelay:2];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
            
        }];
        
    });
    
    
    
}
- (IBAction)timeSelected:(UIButton *)btn {
    
    _selectedTimeBtn=btn;
    [self datePickerShow];
    
}
#pragma mark -  店铺主图点击
- (IBAction)merchatMainPicSelect:(id)sender {
    _mainPhotoSelected=YES;
    if (self.mainImage) {
        //预览
        [ImageBrowserManager viewController:self pushToBrowserWithPhotos:@[_mainImage]];
    }
    else  [self selectPhotos];
    
}
//重新选择主图
- (IBAction)merchantMainPicClose:(id)sender {
    _mainPhotoSelected=YES;
    [self selectPhotos];
}


-(void)selectPhotos{
    
    XXSheetView *sheet=[XXSheetView sheetViewWithTitle:nil redButtonTitle:@"" otherbuttonTitle:@[@"从相册选择",@"拍一张"]];
    sheet.sheetViewOtherButtonClickBlock=^(NSUInteger index,NSString *title){
        if(index==0){
            if(_mainPhotoSelected==YES){
                if ([[ImagePickerTool sharedManager] sourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]==YES) {
                    UIImagePickerController *cameraController=[ImagePickerTool  imagePickerController];
                    [self presentViewController:cameraController animated:YES completion:nil];
                    
                }
                
            }
            else{
                ASSETHELPER.limitSelectCount=5;
                JFImagePickerController *picker = [[JFImagePickerController alloc]initWithRootViewController:self];
                picker.pickerDelegate = self;
                [self presentViewController:picker animated:YES completion:nil];
                
            }
        }
        if(index==1){
            //相机
            
            if ([[ImagePickerTool sharedManager] sourceTypeAvailable:UIImagePickerControllerSourceTypeCamera ]==YES) {
                UIImagePickerController *cameraController=[ImagePickerTool  cameraController];
                [self presentViewController:cameraController animated:YES completion:nil];
                
            }
        }
        
    };
    [sheet showSheetView];
    
}
#pragma mark -
#pragma mark PrivateMethod
//访问相册
//-(void)visitPhotoAlbum{
//    JFImagePickerController *picker = [[JFImagePickerController alloc]initWithRootViewController:self];
//    picker.pickerDelegate = self;
//    [self presentViewController:picker animated:YES completion:nil];
//
//}
-(void)datePickerShow
{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        self.datePicker.transform=CGAffineTransformMakeTranslation(0, -datePickerH);
    }];
    
}
-(void)datePickerHidden
{
    [UIView animateWithDuration:0.5 animations:^{
        self.datePicker.transform=CGAffineTransformIdentity;
    }];
    
}

-(BOOL)isMerchantInfoComplete{
    if (!_mainImage) {
        showTipHudStr(@"请选择店铺主图");
        return NO;
    }
    if (!(self.photoBrowseView.photos.count>0)) {
        showTipHudStr(@"请选择店铺展示图");
        return NO;
    }
    
    if (!(_merchantModel.openTime.length>0&&_merchantModel.closeTime.length>0)) {
        showTipHudStr(@"请选择营业时间");
        return NO;
    }
    if (!(_merchantModel.intro.length>0)) {
        showTipHudStr(@"请输入店铺介绍");
        return NO;
    }
    if (!(_merchantModel.phone.length>0||[NSString judgeMobileNumberValid:_merchantModel.phone ]==NO)) {
        showTipHudStr(@"请输入正确的电话号码");
        return NO;
    }
    
    return YES;
}
//刷新相册数据
-(void)refreshAlbumWithAddImage:(UIImage *)image{
    
//    ASSETHELPER.isFirstOpenCamera=YES;
    [ASSETHELPER getSavedPhotoList:^(NSArray *r) {
        NSMutableArray *photos=[NSMutableArray array];
        [ASSETHELPER.selectdAssets addObject:[[ASSETHELPER assetPhotos] firstObject]];
        
        [ASSETHELPER.selectdPhotos enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [photos addObject:@{@"indexpath":@([dict[@"indexpath"] intValue]+1),@"location":@(idx+1)}];
            NSLog(@"%@",dict);
            
            
        }];
        [photos addObject:@{@"indexpath":@0,@"location":@0}];//添加新拍的那张
        
        NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:@"location" ascending:YES];
        [photos sortUsingDescriptors:@[desc]];
        
        ASSETHELPER.selectdPhotos =[NSMutableArray arrayWithArray:photos];
  
    } error:nil];
//    [ASSETHELPER getPhotoListOfGroupByIndex:ASSETHELPER.currentGroupIndex result:^(NSArray *r) {
////        ASSETHELPER.isFirstOpenCamera=NO;
//        //更新坐标
//        
//    }];
    
#pragma clang diagnostic pop
    
    
}
#pragma mark - 定位
- (void)findMe
{
    /** 由于IOS8中定位的授权机制改变 需要进行手动授权
     * 获取授权认证，两个方法：
     * [self.locationManager requestWhenInUseAuthorization];
     * [self.locationManager requestAlwaysAuthorization];
     */
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestAlwaysAuthorization];
    
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        
        [self.locationManager requestAlwaysAuthorization];
    }
    
    //开始定位，不断调用其代理方法
    [self.locationManager startUpdatingLocation];
    
}
//判断当前位置是否开启
-(BOOL )isLocationOpen{
    //请开启定位服务
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status)
    {
        [self showAlert];
        return NO;
    }else
    {
        //开启的
        return YES;
    }
    
}
-(void)showAlert{
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
    UIAlertView * positioningAlertivew = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"当前需要您的位置信息,请到设置->隐私->定位服务中开启!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
    
    [positioningAlertivew show];
#pragma clang diagnostic pop
}
#pragma mark -
#pragma mark Setter&&Getter
-(void)setMainImage:(UIImage *)mainImage{
    if (mainImage) {
        _mainImage=mainImage;
        [_mainPhotoButton setImage:mainImage forState:UIControlStateNormal];
        _mainPhotoCloseButton.hidden=NO;
    }
    
}

+ (UIViewController *)storyboardInstance {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MerchantManagement" bundle:nil];
    return [sb controller:self];
}
-(GYZDatePicker *)datePicker
{
    if (_datePicker==nil) {
        
        _datePicker = [[GYZDatePicker alloc]
                       initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, datePickerH)
                       delegate:self
                       datePickerStyle:GYZDatePickerStyleHourMinute];
        [kKeyWindow addSubview:_datePicker];//加在当前窗口上
        __weak typeof(_datePicker)wdatePicker = _datePicker;
        
        _datePicker.datePickerBlock=^{
            //完成隐藏
            [UIView animateWithDuration:0.5 animations:^{
                wdatePicker.transform=CGAffineTransformMakeTranslation(0, datePickerH);
            }];
            
        };
        
    }
    return _datePicker;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
